from rest_framework.views import APIView
from rest_framework.response import Response
from utils.response import APIResponse


from . import serializers

# 需要登录后才能访问
from rest_framework_jwt.authentication import JSONWebTokenAuthentication
from rest_framework.permissions import IsAuthenticated


class PayAPIView(APIView):
    authentication_classes = [JSONWebTokenAuthentication]
    permission_classes = [IsAuthenticated]

    def post(self, request, *args, **kwargs):
        serializer = serializers.OrderModelSerializer(
            data=request.data, context={'request': request})

        # 信息校验
        serializer.is_valid(raise_exception=True)
        # 订单入库
        serializer.save()
        # 返回一个支付链接
        return Response(serializer.pay_url)


# 支付宝 同步回调接口(patch方法) 异步回调接口(post方法)
from libs.iPay import alipay
from . import models
from utils.logging import logger


class SuccessAPIView(APIView):
    # 重点：要不要做登录认证，不需要：订单号可以获取你所需要的所有信息、回调参数有自己的安全校验、支付宝永远不可能通过token
    def patch(self, request, *args, **kwargs):
        data = request.query_params.dict()
        sign = data.pop('sign')
        result = alipay.verify(data, sign)
        if result:
            # 一般不在同步回调直接操作订单状态
            pass
        return Response('同步回调完成')

    # 异步支付宝回调接口：公网下才能验证
    def post(self, request, *args, **kwargs):
        data = request.data.dict()  # 回调参数，是QueryDict类型，不能直接调用pop方法
        sign = data.pop('sign')  # 签名
        out_trade_no = data.get('out_trade_no')  # 订单号
        result = alipay.verify(data, sign)
        if result and data["trade_status"] in ("TRADE_SUCCESS", "TRADE_FINISHED"):
            try:
                order = models.Order.objects.get(out_trade_no=out_trade_no)
                if order.order_status != 1:
                    order.order_status = 1
                    order.save()
                    logger.warning('%s订单完成支付' % out_trade_no)
                return Response('success')
            except:
                pass
        return Response('failed')

# 订单群查
from rest_framework.generics import ListAPIView
from .filters import OrderFilterSet
# OrderingFilter排序， SearchFilter搜索
from rest_framework.filters import OrderingFilter,SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
class OrderListAPIView(ListAPIView):
    queryset = models.Order.objects.filter(
        is_delete=False, is_show=True
    ).all()
    serializer_class = serializers.OrderListModelSerializer

    #配置过滤器
    filter_backends = [OrderingFilter, SearchFilter, DjangoFilterBackend]

    filter_class = OrderFilterSet

# 订单详情群查
from .filters import OrderDetailFilterSet
# OrderingFilter排序， SearchFilter搜索
from rest_framework.filters import OrderingFilter,SearchFilter
from django_filters.rest_framework import DjangoFilterBackend
class OrderDetailListAPIView(ListAPIView):
    queryset = models.OrderDetail.objects.filter(
        is_delete=False, is_show=True
    ).all()
    serializer_class = serializers.OrderDetailListModelSerializer

    #配置过滤器
    filter_backends = [OrderingFilter, SearchFilter, DjangoFilterBackend]

    filter_class = OrderDetailFilterSet




# # 订单投诉单查
# from rest_framework.generics import RetrieveAPIView
# import user.models as Umodels
# class OrderComplainAPIView(RetrieveAPIView):
#     queryset = Umodels.Complain.objects.all()
#     serializer_class = serializers.OrderComplainModelSerializer


